// pages/login/login.ts
import {
  PAGE_PHONE_VERIFICATION,
  PAGE_PRIVACY_POLICY,
  PAGE_DISCLAIMER,
  goToPage,
  handleLoginSuccess,
  PAGES
} from '../../../config/pages';
import Routine from "../../../libs/routine";
import {authLogin, authType} from "../../../api/public";
import {getUserInfo} from "../../../api/user";
import store from "../../../store/index.js";
import util from "../../../utils/util";
import cache from "../../../utils/cache";

Page({
  data: {
    agreementAccepted: false
  },

  onLoad(options: any) {
    console.log('登录页面加载完成');
    
    const app = getApp();
    
    // 处理邀请链接参数
    if (options && options.spread) {
      const spreadUid = parseInt(options.spread);
      if (spreadUid > 0) {
        app.globalData.spid = spreadUid;
        console.log('登录页面获取推广人ID:', spreadUid);
        
        // 保存到缓存
        wx.setStorageSync('invite_spread_uid', spreadUid);
        
        // 显示提示
        wx.showToast({
          title: '通过好友邀请进入',
          icon: 'none',
          duration: 2000
        });
      }
    }
    
    // 如果缓存中有邀请人ID，也设置到globalData
    const cachedSpreadUid = wx.getStorageSync('invite_spread_uid');
    if (cachedSpreadUid && !app.globalData.spid) {
      app.globalData.spid = cachedSpreadUid;
      console.log('从缓存获取推广人ID:', cachedSpreadUid);
    }
    
    // 登录页面不需要检查登录状态，避免重复跳转
  },

  onShow() {
    console.log('登录页面显示');
  },

  // 切换用户协议状态
  toggleAgreement() {
    this.setData({
      agreementAccepted: !this.data.agreementAccepted
    });
  },

  userLogin() {
    const app = getApp()

    if (!this.data.agreementAccepted) {
      wx.showToast({
        title: '请先同意用户协议',
        icon: 'none'
      });
      return;
    }
    Routine.getCode()
        .then(code => {
          wx.showLoading({
          	title: (`正在登录中`)
          });
          authType({
            code,
            spread_spid: app.globalData.spid,
            spread_code: app.globalData.code,
          }).then(res => {
            if (!res.data.bindPhone) {
              authLogin({
                key: res.data.key
              }).then(res => {
                let time = res.data.expires_time - cache.time();
                store.commit('app/LOGIN', {
                  token: res.data.token,
                  time: time
                });
                this.getUserInfo(res.data.bindName)
              })
            } else {
              wx.hideLoading();
              goToPage(PAGE_PHONE_VERIFICATION, {
                authKey: res.data.key
              });
            }

          })
              .catch(err => {
                wx.hideLoading();
                wx.showToast({
                  title: err,
                  icon: 'none',
                  duration: 2000
                });
              });
        })
        .catch(err => {
          console.log(err)
        });
  },

  getUserInfo: function(new_user) {
    let that = this;
    getUserInfo().then(res => {
      wx.hideLoading();
      // that.userInfo = res.data
      store.commit("app/SETUID", res.data.uid);
      store.commit("app/UPDATE_USERINFO", res.data);
      util.Tips({
        title: (`登录成功`),
        icon: 'success'
      }, {
        tab: 4,
        url: PAGES.HOME
      })

    });
  },

  // 登录成功
  loginSuccess() {
    wx.showToast({
      title: '登录成功！',
      icon: 'success'
    });
    
    // 设置登录状态
    wx.setStorageSync('isLoggedIn', true);
    
    // 跳转到主页
    setTimeout(() => {
      handleLoginSuccess();
    }, 1500);
  },

  // 打开隐私政策
  openPrivacyPolicy() {
    goToPage(PAGE_PRIVACY_POLICY);
  },

  // 打开服务协议
  openServiceAgreement() {
    goToPage(PAGE_DISCLAIMER);
  }
});
